package com.hnichr.ping.demo;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

public class SendMain {
    private static final String appKey = "Wg50hG92";
    private static final String appSecret = "401b5d45b72e85b9ce9e2adef27c04c7387b53e5";


    public static void main(String [] arg){
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("appKey",appKey);
        treeMap.put("mobiles","18637109325");
        //treeMap.put("smsContent","截至目前您共有100项重点工作，已完成60项，逾期40项，结项率60%。具体完成情况您可登录微信小程序“河南人才集团数字化平台”查看。");
        treeMap.put("smsContent","截至目前您共有5项重点工作，已完成2项，逾期0项，结项率0%。具体完成情况您可登录微信小程序“河南人才集团数字化平台”查看。");

        treeMap.put("timestamp",String.valueOf(new Date().getTime()));
        treeMap.put("nonce",uuid());
        treeMap.put("signatureMethod","HMAC-SHA1");
        String signature = getSignature(treeMap);
        treeMap.put("signature",signature);

        HttpResponse response = HttpUtil.createPost("https://ping.hn-talent.com/send/v1/sendSms").contentType("application/json").body(JSON.toJSONString(treeMap)).execute();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>"+response.body());
        System.out.println(">>>>>>>>>>>>>>>>>>>>>OK");
    }

    public static String uuid(){
        String s= UUID.randomUUID().toString();
        return s.replace("-", "");
    }

    public static String getSignature(TreeMap<String,String> treeMap){
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(appSecret.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }
}
